<template>
  <div style="min-width: 829px">
    <div v-if="$route.path == '/goodsOrder'">
      <div class="vs-search-box">
        <el-form ref="form" :inline="true" :model="paging" label-width="110px">
          <el-form-item label="商品名称：">
            <el-input
              style="width: 200px"
              placeholder=""
              v-model="paging.goods_name"
            ></el-input>
          </el-form-item>
          <el-form-item label="手机号码：">
            <el-input
              style="width: 200px"
              placeholder=""
              v-model="paging.phone"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户昵称：">
            <el-input
              style="width: 200px"
              placeholder=""
              v-model="paging.username"
            ></el-input>
          </el-form-item>
          <el-form-item label="" class="vs-right-btns">
            <el-button @click="reset">重置</el-button>
            <el-button @click="handleCurrentChange(1)" type="primary"
              >查询</el-button
            >
          </el-form-item>
          <el-form-item label="订单创建时间：">
            <el-date-picker
              v-model="paging.create_time"
              type="date"
              style="width: 200px"
              value-format="yyyy-MM-dd"
              placeholder="选择日期"
            >
            </el-date-picker>
          </el-form-item>
          <!-- <el-form-item label="付款状态：">
            <el-select
              style="width: 200px"
              clearable
              v-model="paging.pay_status"
              placeholder=""
            >
              <el-option label="已付款" :value="1"> </el-option>
              <el-option label="未付款" :value="2"> </el-option>
            </el-select>
          </el-form-item> -->
          <!-- 订单状态\r\n1: 待付款\r\n2: 待发货\r\n3: 待收货\r\n4: 已完成\r\n5: 已取消\r\n6: 退款中\r\n7: 已退款\r\n8: 已评价\r\n9: 部分退款\r\n10: 待消费 -->
          <el-form-item label="订单状态：">
            <el-select
              style="width: 200px"
              clearable
              v-model="paging.status"
              placeholder=""
            >
              <!-- <el-option label="待付款" :value="1"> </el-option> -->
              <el-option label="待发货" :value="2"> </el-option>
              <el-option label="待收货" :value="3"> </el-option>
              <el-option label="已完成" :value="4"> </el-option>
              <!-- <el-option label="已取消" :value="5"> </el-option> -->
              <el-option label="退款中" :value="6"> </el-option>
              <el-option label="已退款" :value="7"> </el-option>
              <el-option label="已评价" :value="8"> </el-option>
              <el-option label="部分退款" :value="9"> </el-option>
              <el-option label="待消费" :value="10"> </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div class="vs-table-box">
        <div class="operation-box clear-float">
          <!-- <el-button   @click="openInfo" type="primary">订单自提货</el-button> -->
          <el-button
            style="margin-left: auto"
            :loading="isDerive"
            @click="derive"
            >导出</el-button
          >
        </div>
        <el-table
          v-loading="loading"
          :data="tableData"
          header-row-class-name="has-gutter-table"
          style="width: 100%"
        >
          <el-table-column
            prop="out_trade_no"
            label="订单编号"
          ></el-table-column>
          <el-table-column label="用户昵称">
            <template slot-scope="scope" v-if="scope.row.user">
              {{ scope.row.user.username }}
            </template>
          </el-table-column>
          <el-table-column label="手机号">
            <template slot-scope="scope" v-if="scope.row.user">
              {{ scope.row.user.phone }}
            </template>
          </el-table-column>
          <el-table-column label="商品名称">
            <template slot-scope="scope">
              <div class="vs-partition">
                <span v-for="item in scope.row.goods" :key="item.id">{{
                  item.goods_name
                }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="订单总额（元）">
            <template slot-scope="scope">
              {{ scope.row.orders_payable }}
            </template>
          </el-table-column>
          <el-table-column prop="create_time" label="订单创建时间">
          </el-table-column>
          <el-table-column label="订单状态">
            <template slot-scope="scope">
              {{ scope.row.status | orderStatus }}
            </template>
          </el-table-column>
          <!-- <el-table-column label="备注">
                    <template slot-scope="scope">
                    <span v-if="scope.row.reserve">
                        {{scope.row.reserve.remark}}
                    </span>
                     </template>
                </el-table-column> -->
          <!-- <el-table-column label="开票状态">
                </el-table-column> -->
          <el-table-column fixed="right" width="160" label="操作">
            <template slot-scope="scope">
              <span @click="setRow(1, scope.row)" class="tab-table-text"
                >详情</span
              >
              <span
                v-if="scope.row.is_invoice == 0 &&(scope.row.pay_type == 2||scope.row.pay_type == 3||scope.row.pay_type == 4||scope.row.pay_type == 5) && 
                (scope.row.status == 4 || scope.row.status == 8)"
                @click="setRow(5, scope.row)"
                class="tab-table-text"
                >开票</span
              >
              <!-- <span v-if="scope.row.status==2" @click="setRow(2,scope.row)" class="tab-table-text">发货</span> -->
              <span
                v-if="
                  scope.row.status == 2 ||
                  scope.row.status == 3 ||
                  scope.row.status == 4 ||
                  scope.row.status == 8 ||
                  scope.row.status == 9
                "
                @click="setRow(3, scope.row)"
                class="tab-red-text"
                >退款</span
              >
            </template>
          </el-table-column>
        </el-table>
        <div class="vs-paging-box">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="paging.page"
            :page-size="paging.limit"
            layout="sizes,prev, pager, next, jumper"
            :total="paging.total"
          >
          </el-pagination>
        </div>
      </div>
    </div>
    <router-view></router-view>
    <el-dialog title="分销记录" :visible.sync="isInfo">
      <!-- width="570px" -->
      <el-table
        :data="recordList"
        v-loading="loading2"
        header-row-class-name="has-gutter-table"
        style="width: 100%"
      >
        <el-table-column prop="company.title" label="公司名称">
        </el-table-column>
        <el-table-column prop="create_time" label="邀请时间"> </el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="isInfo = false">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="申请退款"
      :visible.sync="dialogVisible"
      :before-close="handleClose"
    >
      <el-form
        ref="form"
        v-if="order.user"
        :model="form"
        :rules="rules"
        label-width="120px"
      >
        <el-form-item label="订单编号：" prop="use_status">
          {{ order.out_trade_no }}
        </el-form-item>
        <el-form-item label="顾客项目：" prop="use_status">
          {{ order.user.username }}
        </el-form-item>
        <el-form-item label="手机号码：" prop="use_status">
          {{ order.user.phone }}
        </el-form-item>
        <el-form-item label="可退款金额：" prop="use_status">
          {{ order.orders_payable - order.return_money }}
        </el-form-item>
        <el-form-item label="退款金额：" prop="return_money">
          <el-input
            v-model.number="form.return_money"
            @input="priceInput"
            placeholder="请输入退款金额"
          ></el-input>
        </el-form-item>
        <el-form-item label="退款原因：" prop="return_remark">
          <el-input
            type="textarea"
            :rows="5"
            v-model="form.return_remark"
            placeholder="请输入退款金额"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose()">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      recordList: [],
      loading: false,
      loading2: false,
      isBtn: false,
      isInfo: false,
      dialogVisible: false,
      paging: {
        goods_name: "", //商品名称
        phone: "", //手机号
        username: "", //用户昵称
        create_time: "", //订单创建时间 年-月-日
        pay_status: "", //付款状态 1：已付款  2：未付款
        status: "", //订单状态
        page: 1,
        total: 0,
        limit: 10,
        is_export: 0,
      },
      order: {},
      rules: {
        return_money: {
          required: true,
          message: "请输入退款金额",
          trigger: "blur",
        },
        return_remark: {
          required: true,
          message: "请输入退款备注",
          trigger: "blur",
        },
      },
      isDerive: false,
      form: {
        id: "", //订单id
        return_money: "", //退款金额
        return_remark: "", //退款备注
      },
      tableData: [],
    };
  },
  created() {
    if (this.$route.path == "/goodsOrder") {
      this.handleCurrentChange(1);
    }
  },
  methods: {
    async derive() {
      console.log(this.utils.data.baseURL);
      // return;
      this.isDerive = true;
      let res = await this.$Http.exportOrdersGoods(this.paging);
      console.log(res, "@@@@@");
      this.isDerive = false;
      this.utils.downloadXlsx(res);
      // var a = document.createElement('a');
      // // a.download = "oldFileName";
      // a.href = this.utils.data.baseURL+'admin/goods/getOrders?is_export=1';
      // document.body.appendChild(a); // 修复firefox中没法触发click
      // a.click();
      // document.body.removeChild(a);
      // console.log(res,'@@@');
    },
    priceInput() {
      if (
        this.form.return_money >
        this.order.orders_payable - this.order.return_money
      ) {
        this.form.return_money =
          this.order.orders_payable - this.order.return_money;
      }
    },
    openInfo() {
      this.$prompt("请输入核验码", "商品自提", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputPattern: /^\d+$/,
        inputErrorMessage: "核验码格式不正确",
        closeOnClickModal: false,
        beforeClose: async (action, instance, done) => {
          console.log(instance, "actionactionaction");
          if (action === "confirm") {
            // if(!instance.inputValue)return this.$message.error('');
            instance.confirmButtonLoading = true;
            instance.confirmButtonText = "执行中...";
            let { code, data } = await this.$Http.setDelivery({
              check_code: instance.inputValue,
            });
            if (code) {
              this.$message.success("提交成功!");
              this.handleCurrentChange(1);
            }
            done();
            instance.confirmButtonLoading = false;
          } else {
            done();
          }
        },
      })
        .then(({ value }) => {})
        .catch(() => {});
    },
    submit() {
      //退款
      this.$refs["form"].validate(async (valid) => {
        if (!valid) return;
        let obj = Object.assign({}, this.form);
        let { code, data } = await this.$Http.ordersReturn(obj);
        if (code) {
          this.$message.success("提交成功!");
          this.handleCurrentChange(1);
          this.handleClose();
        }
      });
    },
    async setRow(type, row) {
      if (type == 1) {
        this.utils.goUrl("/goodsOrderInfo?id=" + row.id);
      } else if (type == 2) {
        let { code, data } = await this.$Http.setDeliverGoods({
          orders_id: row.id,
        });
        if ((code, data)) {
          this.$message.success("发货成功!");
          this.handleCurrentChange(1);
        }
      } else if (type == 5) {
        if (row.isEnd) {
          this.$message.warning("此次消费开票有效期为30天");
          return;
        }
        this.utils.goUrl(
          `/makeGoodsInvoice?company_id=${row.store.company_id}&orders_id=${row.id}&price=${row.orders_payable}`
        );
      } else {
        // this.dialogVisible = true;
        // this.order = row;
        // this.form.id = row.id;
        // this.form.return_money = row.return_money;
        this.$msgbox({
          title: "提示",
          message: "确定要退款该商品吗?",
          type: "warning",
          showCancelButton: true,
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          beforeClose: async (action, instance, done) => {
            if (action === "confirm") {
              instance.confirmButtonLoading = true;
              instance.confirmButtonText = "执行中...";
              let { code, data } = await this.$Http.setReturnGoods({
                orders_goods_id: row.goods.map((v) => v.id).join(","),
                orders_id: row.id,
              });
              if (code) {
                this.$message.success("退款成功!");
                this.repairGetList();
              }
              done();
              instance.confirmButtonLoading = false;
            } else {
              done();
            }
          },
        })
          .then((action) => {})
          .catch(() => {});
      }
    },
    handleClose(dom) {
      this.form = this.$options.data().form;
      this.$refs["form"].resetFields();
      this.dialogVisible = false;
      dom && dom();
    },
    async repairGetList() {
      let obj = Object.assign({}, this.paging);
      // if(obj.create_time) obj.create_time /= 1000;
      this.loading = true;
      let { code, data } = await this.$Http.getgoodsOrders(obj);
      this.loading = false;
      if (code) {
        data.data.forEach((v) => {
          v.isEnd = false;
          if (v.pay_time) {
            // 起止时间
            let presentTime = Date.parse(new Date()) / 1000;
            // 截止时间
            var date = new Date(v.pay_time);
            var time = new Date(
              date.setDate(date.getDate() + 30)
            ).toLocaleDateString(); //获取当前日期后加30天
            let getEndTime = new Date(time);
            let endTime = Date.parse(getEndTime) / 1000;
            if (presentTime > endTime) {
              v.isEnd = true;
            }
            console.log(presentTime, endTime, v.isEnd);
          }
        });
        this.tableData = data.data;
        this.paging.total = data.total;
      }
    },
    reset() {
      //重置
      this.paging = this.$options.data().paging;
      this.form.date = "";
      this.handleCurrentChange(1);
    },
    handleSizeChange(val) {
      this.paging.limit = val;
      this.repairGetList();
    },
    handleCurrentChange(val) {
      this.paging.page = val;
      this.repairGetList();
    },
  },
};
</script>

<style lang="scss" scoped>
.image-thumbnail {
  width: 130px;
  height: 130px;
}
</style>